package com.zjy.service.impl;

import com.zjy.bean.User;
import com.zjy.dao.UserMapper;
import com.zjy.dto.UserInfo;
import com.zjy.service.UserService;
import com.zjy.utils.TokenUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Administrator on 2019/2/26.
 */
@Service
public class UserServiceImpl implements UserService{
    @Resource
    private UserMapper userMapper;

    @Override
    public int checkExistUserName(String userName) {
        return userMapper.checkExistUserName(userName);
    }

    @Override
    public int checkPassword(User user) {
        return userMapper.checkPassword(user);
    }

    @Override
    public UserInfo getUserInfo(User user) {
        String id = user.getId();
        String userName = user.getUserName();
        String token = TokenUtils.createTokenByUserId(id);  //利用userId生成一个token返回给客户端浏览器
        UserInfo userInfo = new UserInfo(id,userName,token);    //创建一个包含userId和token的实体
        return userInfo;
    }

    @Override
    public int updateUserById(User user) {
        return userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public int updatePassword(User user) {
        return userMapper.updatePassword(user);
    }

    @Override
    public User selectUserById(String userId) {
        return userMapper.selectUserById(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HashMap<String, Object> getUserNum() {
        HashMap<String,Object> map = new HashMap<>();
        int todayCount = 0;
        int totalCount = 0;
        //不传入时间则为查询所有用户
        List<User> allUserList = userMapper.selectUserList("","");
        if(allUserList != null){
            totalCount = allUserList.size();
        }
        Date date = new Date(); //获取当前的系统时间。
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");//今天零点
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//当前时间
        String begin = dateFormat1.format(date) + " 00:00:00";
        String now = dateFormat2.format(date);
        //不传入时间则为查询所有用户
        List<User> todayUserList = userMapper.selectUserList(begin,now);
        if(todayUserList != null){
            todayCount = todayUserList.size();
        }
        map.put("totalCount",totalCount);
        map.put("todayCount",todayCount);
        return map;
    }


}
